package com.mojian.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.mojian.common.Constants;
import com.mojian.entity.SysArticle;
import com.mojian.exception.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.mojian.mapper.SysMomentMapper;
import com.mojian.entity.SysMoment;
import com.mojian.service.SysMomentService;
import com.mojian.utils.PageUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;

import java.util.List;

/**
 * 说说 服务实现类
 */
@Service
@RequiredArgsConstructor
public class SysMomentServiceImpl extends ServiceImpl<SysMomentMapper, SysMoment> implements SysMomentService {

    /**
     * 查询说说分页列表
     */
    @Override
    public IPage<SysMoment> selectPage(SysMoment sysMoment) {
        return page(PageUtil.getPage(), new LambdaQueryWrapper<SysMoment>()
                .orderByDesc(SysMoment::getCreateTime));
    }

    @Override
    public Object add(SysMoment sysMoment) {
        sysMoment.setUserId(StpUtil.getLoginIdAsLong());
        return save(sysMoment);
    }

    @Override
    public Boolean update(SysMoment sysMoment) {
        SysMoment obj = new SysMoment();
        BeanUtils.copyProperties(sysMoment, obj);

        //没有管理员权限就只能修改自己的文章
        if (!StpUtil.hasRole(Constants.ADMIN)) {
            SysMoment article = baseMapper.selectById(sysMoment.getId());
            if (article.getUserId() != StpUtil.getLoginIdAsLong()) {
                throw new ServiceException("只能修改自己的说说");
            }
        }

        baseMapper.updateById(obj);
        return true;
    }

    @Override
    public Boolean delete(List<Long> ids) {
        //没有管理员权限就只能删除自己的说说
        if (!StpUtil.hasRole(Constants.ADMIN)) {
            List<SysMoment> sysMoments = baseMapper.selectBatchIds(ids);
            for (SysMoment sysArticle : sysMoments) {
                if (sysArticle.getUserId() != StpUtil.getLoginIdAsLong()) {
                    throw new ServiceException("只能删除自己的说说");
                }
            }
        }


        baseMapper.deleteBatchIds(ids);
        return true;
    }


}
